package com.ruoyi.yipaiju.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.domain.entity.XcxUser;
import com.ruoyi.common.core.page.TableDataApi;
import com.ruoyi.common.utils.CurrencyUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.yipaiju.domain.*;
import com.ruoyi.yipaiju.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 优选
 */
@RestController
@RequestMapping("/houses")
public class HousesForeclosedController extends BaseController {

    /**
     * type==1?'优选':'折扣'
     * 优选房源  == 法拍房
     */

    @Autowired
    private IForeclosedHouseService foreclosedHouseService;
    @Autowired
    private IFavoriteService favoriteService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IForeclosedHouseBookingorderService foreclosedHouseBookingorderService;
    @Autowired
    private IForeclosedHouseBookingorderFollowerService foreclosedHouseBookingorderFollowerService;
    @Autowired
    private IXcxUserService xcxUserService;

    @Autowired
    private IForeclosedHouseSigningorderService foreclosedHouseSigningorderService;


    /**
     * http://127.0.0.1:8071/api/public/v1/houses/foreclosed?
     * start_time=2023-02-25&
     * province=%E4%B8%8A%E6%B5%B7&city=%E4%B8%8A%E6%B5%B7%E5%B8%82&district=%E6%B5%A6%E4%B8%9C%E6%96%B0%E5%8C%BA&
     * areaMin=130&
     * areaMax=99999999&
     * priceMin=8000000&
     * priceMax=12000000&
     * startTime=2023-02-25
     *
     * @param foreclosedHouse
     * @return
     */
    /**
     * 优选房源列表
     * @param foreclosedHouse
     * @return
     */
    @GetMapping("/foreclosed")
    public TableDataApi foreclosed(ForeclosedHouse foreclosedHouse) {
        startPageApi();
//        if (foreclosedHouse.getStatusArr() == null){
//            foreclosedHouse.setStatusArr("预告中,进行中".split(","));
//        }
        List<ForeclosedHouse> foreclosedHouses = foreclosedHouseService.selectForeclosedHouseList(foreclosedHouse);
        return getTableApi(foreclosedHouses);
    }

    /**
     * 优选房源详情
     * @param id
     * @return
     */
    @GetMapping(value = "/foreclosed/{id}")
    public ApiResult foreclosedInfo(@PathVariable("id") Long id)
    {
        ForeclosedHouse foreclosedHouse = foreclosedHouseService.selectForeclosedHouseById(id);
//        announcement, notice, description
        int loadLen = 500;
        if (StringUtils.isNotEmpty(foreclosedHouse.getAnnouncement())){
            int announcementIndex = foreclosedHouse.getAnnouncement().indexOf("加载中......");
            if (announcementIndex > 0 && announcementIndex < loadLen){
                foreclosedHouse.setAnnouncement(null);
            }
        }
        if (StringUtils.isNotEmpty(foreclosedHouse.getNotice())){
            int noticeIndex = foreclosedHouse.getNotice().indexOf("加载中......");
            if (noticeIndex > 0 && noticeIndex < loadLen){
                foreclosedHouse.setNotice(null);
            }
        }
        if (StringUtils.isNotEmpty(foreclosedHouse.getDescription())){
            int descriptionIndex = foreclosedHouse.getDescription().indexOf("加载中......");
            if (descriptionIndex > 0 && descriptionIndex < loadLen){
                foreclosedHouse.setDescription(null);
            }
        }

        try {
            //获取用户是否收藏
            Favorite favorite = favoriteService.selectOneFavorite(Builder.of(Favorite::new)
                    .with(Favorite::setClient, SecurityUtils.getUserId().toString())
                    .with(Favorite::setForeclosedHouseId, id)
                    .build());
            if (favorite == null){
                foreclosedHouse.setIsfavor(0);
            }else {
                foreclosedHouse.setIsfavor(1);
                foreclosedHouse.setFavorId(favorite.getId());
            }

            Notice notice = noticeService.selectOneNotice(Builder.of(Notice::new)
                    .with(Notice::setClient, SecurityUtils.getUserId().toString())
                    .with(Notice::setForeclosedHouseId, id)
                    .build());
            if (notice == null){
                foreclosedHouse.setIsnotice(0);
            }else {
                foreclosedHouse.setIsnotice(1);
                foreclosedHouse.setNoticeId(notice.getId());
            }
        }catch (Exception e){
            logger.error(e.getMessage());
        }

        foreclosedHouse.setOrigin("商业拍卖");
        return ApiResult.success(foreclosedHouse);
    }

    /**
     * 一键预约优选
     * @param foreclosedHouseBookingorder
     * @return
     */
    @PostMapping("/foreclosed/booking/orders")
    public ApiResult foreclosedBookingOrders(@RequestBody ForeclosedHouseBookingorder foreclosedHouseBookingorder){
        ForeclosedHouse foreclosedHouse = foreclosedHouseService.selectForeclosedHouseById(foreclosedHouseBookingorder.getForeclosedHouseId());
        if (foreclosedHouse != null){
            foreclosedHouseBookingorder.setNo(CurrencyUtil.create(10));
            foreclosedHouseBookingorder.setClient(SecurityUtils.getUserId());
            foreclosedHouseBookingorder.setForeclosedHouseTitle(foreclosedHouse.getTitle());
            foreclosedHouseBookingorderService.insertForeclosedHouseBookingorder(foreclosedHouseBookingorder);
            return ApiResult.success();
        }else {
            return ApiResult.error();
        }
    }

    /**
     * 优选预约详情
     * @param id
     * @return
     */
    @GetMapping("/foreclosed/booking/orders/{id}")
    public ApiResult foreclosedBookingOrdersInfo(@PathVariable("id") Long id){
        ForeclosedHouseBookingorder foreclosedHouseBookingorder = foreclosedHouseBookingorderService.selectForeclosedHouseBookingorderById(id);
        foreclosedHouseBookingorder.setForeclosedHouse(foreclosedHouseService.selectForeclosedHouseById(foreclosedHouseBookingorder.getForeclosedHouseId()));

        List<ForeclosedHouseBookingorderFollower> foreclosedHouseBookingorderFollowers = foreclosedHouseBookingorderFollowerService.selectForeclosedHouseBookingorderFollowerList(Builder.of(ForeclosedHouseBookingorderFollower::new).with(ForeclosedHouseBookingorderFollower::setForeclosedHouseBookingorderId, foreclosedHouseBookingorder.getId()).build());
        foreclosedHouseBookingorder.setForeclosedHouseBookingorderFollowers(foreclosedHouseBookingorderFollowers);

        List<Long> ids = foreclosedHouseBookingorderFollowers.stream().map(item -> Long.valueOf(item.getMarketer())).distinct().collect(Collectors.toList());
        Map<Long, XcxUser> xcxUserMap = xcxUserService.getXcxUserByIds(ids);
        foreclosedHouseBookingorderFollowers.stream().forEach(item -> {
            XcxUser xcxUser = xcxUserMap.get(Long.valueOf(item.getMarketer()));
            if (xcxUser != null){
                item.setImg(xcxUser.getAvatarUrl());
                item.setMarkName(xcxUser.getNickname());
                item.setTelphone(xcxUser.getPhone());
            }
        });
        return ApiResult.success(foreclosedHouseBookingorder);
    }

    /**
     * 优选跟单
     * @return
     */
    @PostMapping("/foreclosed/booking/orders/followers")
    public ApiResult foreclosedBookingOrdersFollowers(@RequestBody ForeclosedHouseBookingorderFollower foreclosedHouseBookingorderFollower){
        if (StringUtils.isEmpty(foreclosedHouseBookingorderFollower.getMarketer())){
            foreclosedHouseBookingorderFollower.setMarketer(SecurityUtils.getUserId().toString());
        }
        ForeclosedHouseBookingorderFollower foreclosedHouseBookingorderFollower1 = foreclosedHouseBookingorderFollowerService.selectOneForeclosedHouseBookingorderFollower(foreclosedHouseBookingorderFollower);
        //  TODO 只能一个人接单  这个判断有问题  再说吧

        if (foreclosedHouseBookingorderFollower1 == null){
            foreclosedHouseBookingorderFollower1 = Builder.of(ForeclosedHouseBookingorderFollower::new)
                    .with(ForeclosedHouseBookingorderFollower::setForeclosedHouseBookingorderId, foreclosedHouseBookingorderFollower.getForeclosedHouseBookingorderId())
//                    .with(ForeclosedHouseBookingorderFollower::setMarketer, SecurityUtils.getUserId().toString())
                    .with(ForeclosedHouseBookingorderFollower::setMarketer, foreclosedHouseBookingorderFollower.getMarketer())
                    .with(ForeclosedHouseBookingorderFollower::setStage, 1)
                    .build();
            foreclosedHouseBookingorderFollowerService.insertForeclosedHouseBookingorderFollower(foreclosedHouseBookingorderFollower1);
            ForeclosedHouseBookingorder foreclosedHouseBookingorder = foreclosedHouseBookingorderService.selectForeclosedHouseBookingorderById(foreclosedHouseBookingorderFollower.getForeclosedHouseBookingorderId());
            foreclosedHouseBookingorder.setStage(2);
            foreclosedHouseBookingorder.setServingTime(new Date());
            foreclosedHouseBookingorderService.updateForeclosedHouseBookingorder(foreclosedHouseBookingorder);
        }
        ForeclosedHouseBookingorder foreclosedHouseBookingorder = foreclosedHouseBookingorderService.selectForeclosedHouseBookingorderById(foreclosedHouseBookingorderFollower1.getForeclosedHouseBookingorderId());
        if (foreclosedHouseBookingorder != null) {
            ForeclosedHouse foreclosedHouse = foreclosedHouseService.selectForeclosedHouseById(foreclosedHouseBookingorder.getForeclosedHouseId());
            if (foreclosedHouse != null) foreclosedHouseBookingorder.setForeclosedHouse(foreclosedHouse);
            foreclosedHouseBookingorderFollower1.setForeclosedHouseBookingorder(foreclosedHouseBookingorder);
            return ApiResult.success(foreclosedHouseBookingorderFollower1);
        }
        return ApiResult.error();
    }

    /**
     * 设置备注和下一步状态更新
     * @param id
     * @param foreclosedHouseBookingorderFollower
     * @return
     */
    @PostMapping("/foreclosed/booking/orders/followers/{id}")
    public ApiResult foreclosedBookingOrdersFollowersInfo(@PathVariable("id") Long id, @RequestBody ForeclosedHouseBookingorderFollower foreclosedHouseBookingorderFollower){
        ForeclosedHouseBookingorderFollower foreclosedHouseBookingorderFollower1 = foreclosedHouseBookingorderFollowerService.selectForeclosedHouseBookingorderFollowerById(id);
        if (foreclosedHouseBookingorderFollower1 != null){
            if (foreclosedHouseBookingorderFollower.getRemark() != null){
                foreclosedHouseBookingorderFollower1.setRemark(foreclosedHouseBookingorderFollower.getRemark());
            }
            if (foreclosedHouseBookingorderFollower.getStage() != null){
                foreclosedHouseBookingorderFollower1.setStage(foreclosedHouseBookingorderFollower.getStage());
                if (foreclosedHouseBookingorderFollower.getStage().intValue() == 2){
                    foreclosedHouseBookingorderFollower1.setGetDemandTime(new Date());
                }
                if (foreclosedHouseBookingorderFollower.getStage().intValue() == 3){
                    foreclosedHouseBookingorderFollower1.setOlInviteTime(new Date());
                }

                if (foreclosedHouseBookingorderFollower.getStage().intValue() == 4){
                    foreclosedHouseBookingorderFollower1.setInterviewTime(new Date());
                }
                if (foreclosedHouseBookingorderFollower.getStage().intValue() == 5){
                    foreclosedHouseBookingorderFollower1.setBeforeSignTime(new Date());
                    ForeclosedHouseBookingorder foreclosedHouseBookingorder = foreclosedHouseBookingorderService.selectForeclosedHouseBookingorderById(foreclosedHouseBookingorderFollower1.getForeclosedHouseBookingorderId());
                    foreclosedHouseBookingorder.setStage(3);
                    foreclosedHouseBookingorder.setFinishTime(new Date());
                    foreclosedHouseBookingorder.setFinished(1);
                    foreclosedHouseBookingorderService.updateForeclosedHouseBookingorder(foreclosedHouseBookingorder);
                }
            }

            ForeclosedHouseBookingorder foreclosedHouseBookingorder = foreclosedHouseBookingorderService.selectForeclosedHouseBookingorderById(foreclosedHouseBookingorderFollower1.getForeclosedHouseBookingorderId());
            ForeclosedHouse foreclosedHouse = foreclosedHouseService.selectForeclosedHouseById(foreclosedHouseBookingorder.getForeclosedHouseId());
            foreclosedHouseBookingorder.setForeclosedHouse(foreclosedHouse);
            foreclosedHouseBookingorderFollower1.setForeclosedHouseBookingorder(foreclosedHouseBookingorder);
            foreclosedHouseBookingorderFollowerService.updateForeclosedHouseBookingorderFollower(foreclosedHouseBookingorderFollower1);
            return ApiResult.success(foreclosedHouseBookingorderFollower1);
        }
        return ApiResult.error();
    }

    /**
     * 优选预约生成签约订单
     * @param foreclosedHouseSigningorder
     * @return
     */
    @PostMapping("/foreclosed/signing/orders")
    public ApiResult foreclosedSigningOrders(@RequestBody ForeclosedHouseSigningorder foreclosedHouseSigningorder){
        ForeclosedHouse foreclosedHouse = foreclosedHouseService.selectForeclosedHouseById(foreclosedHouseSigningorder.getForeclosedHouseId());
        if (foreclosedHouse != null){
            foreclosedHouseSigningorder.setNo(CurrencyUtil.create(10));
            foreclosedHouseSigningorder.setClient(SecurityUtils.getUserId());
            foreclosedHouseSigningorder.setType(1);
            foreclosedHouseSigningorder.setMarketerJoinTime(new Date());

            // TODO 不确定对不对。。  这个是对的   此参数为市场专呗，  这里还需要添加财务经理和市场经理
            foreclosedHouseSigningorder.setMarketer(SecurityUtils.getUserId());

            // TODO 设置财务经理 和当前用户同一个组下的财务
//            XcxUser financeXcxUser = xcxUserService.selectOneXcxUser(Builder.of(XcxUser::new)
//                    .with(XcxUser::setGroup_id, SecurityUtils.getLoginUser().getXcxUser().getGroup_id())
//                    .with(XcxUser::setActive_role_id, 3L)  // 这里传财务经理
//                    .with(XcxUser::setRole_code, "renter_finance_manager")  // 这里传财务经理
//                    .build());

            XcxUser financeXcxUser = xcxUserService.selectOneXcxUser(Builder.of(XcxUser::new)
                    .with(XcxUser::setGroup_id, SecurityUtils.getLoginUser().getXcxUser().getGroup_id())
                    .with(XcxUser::setActive_role_id, 4L)  // 这里传后勤经理  风险经理
                    .with(XcxUser::setRole_code, "renter_logistics_manager")  // 这里传后勤经理 风险经理
                    .build());
            if (financeXcxUser != null){
                foreclosedHouseSigningorder.setFinancialManager(financeXcxUser.getId().toString());
            }
            // TODO 设置市场经理 和当前用户同一个组下的市场经理
            XcxUser marketingXcxUser = xcxUserService.selectOneXcxUser(Builder.of(XcxUser::new)
                    .with(XcxUser::setGroup_id, SecurityUtils.getLoginUser().getXcxUser().getGroup_id())
                    .with(XcxUser::setActive_role_id, 2L)  // 这里传市场经理
                    .with(XcxUser::setRole_code, "renter_marketing_manager")  // 这里传市场经理
                    .build());
            if (marketingXcxUser != null){
                foreclosedHouseSigningorder.setMarketManager(marketingXcxUser.getId().toString());
            }

            foreclosedHouseSigningorder.setSubmitTime(new Date());

//            foreclosedHouseSigningorder.setForeclosedHouseTitle(foreclosedHouse.getTitle());
            foreclosedHouseSigningorderService.insertForeclosedHouseSigningorder(foreclosedHouseSigningorder);
            return ApiResult.success(foreclosedHouseSigningorder);
        }else {
            return ApiResult.error();
        }
    }

    /**
     * 优选签约详细
     * @return
     */
    @GetMapping("/foreclosed/signing/orders/{id}")
    public ApiResult foreclosedSigningOrdersInfo(@PathVariable("id") Long id){
        ForeclosedHouseSigningorder foreclosedHouseSigningorder = foreclosedHouseSigningorderService.selectForeclosedHouseSigningorderById(id);
        if (foreclosedHouseSigningorder != null){
            ForeclosedHouse foreclosedHouse = foreclosedHouseService.selectForeclosedHouseById(foreclosedHouseSigningorder.getForeclosedHouseId());
            if (foreclosedHouse != null){
                foreclosedHouseSigningorder.setForeclosedHouse(foreclosedHouse);
            }

            if (foreclosedHouseSigningorder.getMarketer() != null){
                foreclosedHouseSigningorder.setMarketerUser(xcxUserService.selectXcxUserById(foreclosedHouseSigningorder.getMarketer()));
            }
            if (StringUtils.isNotEmpty(foreclosedHouseSigningorder.getFinancialManager())){
                foreclosedHouseSigningorder.setFinancialManagerUser(xcxUserService.selectXcxUserById(Long.parseLong(foreclosedHouseSigningorder.getFinancialManager())));
            }
            if (StringUtils.isNotEmpty(foreclosedHouseSigningorder.getMarketManager())){
                foreclosedHouseSigningorder.setMarketManagerUser(xcxUserService.selectXcxUserById(Long.parseLong(foreclosedHouseSigningorder.getMarketManager())));
            }
            return ApiResult.success(foreclosedHouseSigningorder);
        }
        return ApiResult.error();
    }
}
